package com.itheima.module.util;

import com.alibaba.druid.pool.DruidDataSource;

import javax.sql.DataSource;
import java.io.InputStream;
import java.sql.Connection;
import java.sql.SQLException;
import java.util.Properties;

/**
 * @author huyoufu <https://github.com/huyoufu>
 * @TIME 2021-09-04 23:26
 * @description
 */
public class DataSourceUtil {
    private static final ThreadLocal<Connection> CONNECTION_THREAD_LOCAL=new ThreadLocal<>();
    private static  DataSource dataSource;
    static {
        try {
            InputStream inputStream = DataSourceUtil.class.getClassLoader().getResourceAsStream("db.properties");


            Properties properties = new Properties();

            properties.load(inputStream);


            DruidDataSource druidDataSource = new DruidDataSource();
            druidDataSource.setUsername(properties.getProperty("jdbc.username"));
            druidDataSource.setPassword(properties.getProperty("jdbc.password"));
            druidDataSource.setUrl(properties.getProperty("jdbc.url"));
            druidDataSource.setDriverClassName(properties.getProperty("jdbc.driverClassName"));
            druidDataSource.setMaxActive(Integer.parseInt(properties.getProperty("jdbc.maxActive")));
            druidDataSource.setMinIdle(Integer.parseInt(properties.getProperty("jdbc.minIdle")));
            dataSource=druidDataSource;
        }catch (Exception e){
            throw new RuntimeException("初始化连接池有问题了",e);
        }
    }

    public static DataSource getDataSource(){
        return dataSource;
    }


    public static Connection getConnection(){
        Connection connection=CONNECTION_THREAD_LOCAL.get();
        if (connection==null){
            //第一次使用
            try {
                connection=dataSource.getConnection();
                CONNECTION_THREAD_LOCAL.set(connection);
            } catch (SQLException e) {
                throw new RuntimeException("获取连接失败",e);
            }
        }
        return connection;
    }

    public static void close(){
        Connection connection=CONNECTION_THREAD_LOCAL.get();
        if (connection!=null){
            CONNECTION_THREAD_LOCAL.remove();
            try {
                connection.close();
            } catch (SQLException e) {
                //静默处理
                //e.printStackTrace();
            }
        }
    }




}
